package com.woniuxy.commons.log;

import com.woniuxy.commons.entity.Log;
import com.woniuxy.commons.log.annotation.RequireLog;
import com.woniuxy.commons.rabbbitMQ.provider.DirectProvider;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
@Order(1)
@Aspect
@Component
public class LogAspect {
    @Resource
    private DirectProvider directProvider;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Pointcut("@annotation(com.woniuxy.commons.log.annotation.RequireLog)")
    public void pointcut() { }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
//        ServletRequestAttributes attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = attributes.getRequest();
//        String token = request.getHeader("token");
        // 解析JWT 获取username
        String username = "jack";
        Object result = null;
        long startTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = point.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        // 保存日志
        saveLog(point,username,startTime);
        return result;
    }

    private void saveLog(ProceedingJoinPoint joinPoint,String username,long startTime) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log log = new Log();
        RequireLog logAnnotation = method.getAnnotation(RequireLog.class);
        if (logAnnotation != null) {
            // 注解上的描述
            log.setModule(logAnnotation.module());
            log.setType(logAnnotation.type());
            //设置操作时间
            log.setTime(simpleDateFormat.format(new Date() ) );
            //设置操作用户
            log.setUsername(username);
            //设置消耗时间
            log.setSpan(System.currentTimeMillis()-startTime);
            // 保存系统日志
            directProvider.send(log);
        }
    }
}